package com.zxx.coolweather._wuguan3_ok;

import androidx.appcompat.app.AppCompatActivity;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;

import android.os.Bundle;
import android.text.method.ArrowKeyMovementMethod;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.zxx.coolweather.R;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class OkHttpActivity extends AppCompatActivity {

    private TextView textView;
    private OkHttpClient mOkHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ok_http);
        textView = findViewById(R.id.ok_tv1);
        textView.setMovementMethod(ArrowKeyMovementMethod.getInstance());   //水平滚动
        //textView.setMovementMethod(ScrollingMovementMethod.getInstance());  //垂直滚动

    }


    public void testOk(View view) {
        sampleTest();
        //progressUpload();

        //重试次数
        //testRetryInterceptor();
    }

    static String mUrl = "https://www.baidu.com/";

    static OkHttpClient mClient;

    //重试次数
    private static void testRetryInterceptor() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        mClient = new OkHttpClient.Builder()
                .addInterceptor(new RetryInterceptor(3))//重试
                .addInterceptor(logging)//网络日志
                .addInterceptor(new SelfResponseInterceptor(mUrl))//模拟网络请求
                .build();
    }

    //简单小例子
    private void sampleTest() {
        CacheControl cc = new CacheControl.Builder()
                //不使用缓存，但是会保存缓存数据
                //.noCache()
                //不使用缓存，同时也不保存缓存数据
                // .noStore()
                //只使用缓存，（如果我们要加载的数据本身就是本地数据时，可以使用这个，不过目前尚未发现使用场景）
                //.onlyIfCached()
                //手机可以接收响应时间小于当前时间加上10s的响应
                //                .minFresh(10,TimeUnit.SECONDS)
                //手机可以接收有效期不大于10s的响应
                .maxAge(10, TimeUnit.SECONDS)
                //手机可以接收超出5s的响应
                .maxStale(5, TimeUnit.SECONDS)
                .build();

        Request request = new Request.Builder()
                .cacheControl(cc)
                //或
                //.cacheControl(CacheControl.FORCE_CACHE)
                .url("http://publicobject.com/helloworld.txt")
                .build();

        //mOkHttpClient = new OkHttpClient();
        //或
        mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                //设置缓存:sdcard/Android/data/应用包名/cache/okhttpcache，第二个参数表示缓存区的大小为10M
                .cache(new Cache(new File(this.getExternalCacheDir(), "okHttpcache"), 10 * 1024 * 1024))
                //设置cookie
                .cookieJar(new CookieJar() {

                    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

                    @Override
                    public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
                        cookieStore.put(httpUrl.host(), list);
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl httpUrl) {
                        List<Cookie> cookies = cookieStore.get(httpUrl.host());
                        return cookies != null ? cookies : new ArrayList<Cookie>();
                    }
                })
                .build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("OkHttp", "Call Failed:" + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String body = response.body().string();
                Log.e("OkHttp", "Call succeeded:" + body);
                Log.e("OkHttp", "Call succeeded:" + response.message());
                textView.post(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText(body);
                    }
                });

                //
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }
        });
    }

    //带进度上传文件
    private void progressUpload() {
        new ProgressUploadFile().run(this, new ProgressUploadFile.ProgressListener() {
            @Override
            public void onProgress(long totalBytes, long remainBytes, boolean done) {
                final String str = (totalBytes - remainBytes) * 100 / totalBytes + "%";
                textView.post(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText("上传进度：" + str);
                    }
                });
            }
        });
    }

    //添加cookie
    private void postAsynHttp() {
        mOkHttpClient = new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {
                    private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>();

                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                        cookieStore.put(url, cookies);
                        cookieStore.put(HttpUrl.parse("http://192.168.31.231:8080/shiro-2"), cookies);
                        for (Cookie cookie : cookies) {
                            System.out.println("cookie Name:" + cookie.name());
                            System.out.println("cookie Path:" + cookie.path());
                        }
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        List<Cookie> cookies = cookieStore.get(HttpUrl.parse("http://192.168.31.231:8080/shiro-2"));
                        if (cookies == null) {
                            System.out.println("没加载到cookie");
                        }
                        return cookies != null ? cookies : new ArrayList<Cookie>();
                    }
                })
                .build();

        RequestBody formBody = new FormBody.Builder()
                .add("username", "admin")
                .add("password", "admin")
                .build();

        final Request request = new Request.Builder()
                .url("http://192.168.31.231:8080/shiro-2/shiro-login")
                .post(formBody)
                .build();

        Call call = mOkHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                Log.i("wangshu", str);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "请求成功", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


    public static void main(String[] args) {
        testRetryInterceptor();
        Request request = new Request.Builder()
                .url(mUrl)
                .build();

        try {
            Response response = mClient.newCall(request).execute();

            System.out.println("onResponse:" + response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}